package org.example.listener;

import org.example.model.Message;
import org.example.service.RedisSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQMessageListener.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private RedisSessionService redisSessionService;

    @Value("${spring.application.name}")
    private String serverId;

    @RabbitListener(queues = "#{@websocketQueue}")
    public void handleWebSocketMessage(Message message) {
        logger.info("收到RabbitMQ消息: {}", message.getContent());
        
        // 检查目标用户是否在当前服务器
        if (message.getTargetUserId() != null) {
            String userServer = redisSessionService.getUserServer(message.getTargetUserId());
            if (serverId.equals(userServer)) {
                // 用户在当前服务器，直接发送WebSocket消息
                messagingTemplate.convertAndSendToUser(
                    message.getTargetUserId(), 
                    "/queue/messages", 
                    message
                );
                logger.info("向用户 {} 发送消息: {}", message.getTargetUserId(), message.getContent());
            } else {
                logger.debug("用户 {} 不在当前服务器 {}, 在服务器 {}", 
                    message.getTargetUserId(), serverId, userServer);
            }
        } else if (message.getType() != null && message.getType().equals("broadcast")) {
            // 广播消息
            messagingTemplate.convertAndSend("/topic/broadcast", message);
            logger.info("广播消息: {}", message.getContent());
        }
    }
}